<template>
  <div>
    <el-button @click="open" type="primary" style="margin-top: 10px;margin-left: 10px">
      导入学校用户</el-button>
    <el-table :data="users"
              tooltip-effect="dark"
              style="width: 100%;margin-left: 10px;margin-top: 10px"
              class="myTable">
      <el-table-column prop="id"    label="用户id" v-if="false"></el-table-column>
      <el-table-column fixed prop="name"    label="姓名"></el-table-column>
      <el-table-column prop="role"    label="角色">
        <template slot-scope="scope">
          <span v-if="scope.row.role===1" style="font-size: 15px;">学生</span>
          <span v-else-if="scope.row.role===2" style="font-size: 15px;">教师</span>
        </template>
      </el-table-column>
      <el-table-column prop="age"    label="年龄"></el-table-column>
      <el-table-column prop="gender"    label="性别"></el-table-column>
      <el-table-column prop="grade"    label="成绩">
        <template slot-scope="scope">
          {{ scope.row.grade || '\\' }}
        </template>
      </el-table-column>
      <el-table-column label="所在地" >
        <template slot-scope="scope">
          {{scope.row.province}} {{scope.row.city}}
        </template>
      </el-table-column>
      <el-table-column prop="account"    label="账号"></el-table-column>
      <el-table-column prop="passwd"    label="密码"></el-table-column>
      <el-table-column prop="phone"    label="手机号"></el-table-column>
      <el-table-column prop="email"    label="邮箱"  width="200px"></el-table-column>
    </el-table>

    <el-dialog
        title="导入学校用户"
        :visible.sync="dialogVisible"
        width="40%"
        :before-close="handleClose">
      <!--limit:最大上传数，on-exceed：超过最大上传数量时的操作  -->
      <el-upload
          class="upload-demo"
          action=""
          :on-change="handleChange"
          :on-remove="handleRemove"
          :on-exceed="handleExceed"
          :limit=1
          accept=".xlsx,.xls"
          :auto-upload="false">
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <el-button @click="insertExcel" style="margin-top: 10px">确定上传</el-button>
    </el-dialog>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import * as XLSX from 'xlsx'
import {getNameByUid} from '../../../../api/feekback'
import {getAllUserBySid, insertUser} from '../../../../api/user'

export function readFile (file) {
  return new Promise(resolve => {
    let reader = new FileReader()
    reader.readAsBinaryString(file)
    reader.onload = ev => {
      resolve(ev.target.result)
    }
  })
}
export async function readExcel (file, index) {
  let data = await readFile(file)
  let workbook = XLSX.read(data, {type: 'binary'})
  let worksheet = workbook.Sheets[workbook.SheetNames[index]]
  data = XLSX.utils.sheet_to_json(worksheet)
  return data
}
export default {
  inject: ['reload'],
  name: 'allUser',
  computed: {
    ...mapGetters({
      userType: 'user/getUserRole',
      userAccount: 'user/getUserAccount',
      userId: 'user/getUserId'
    }),
    roleName () {
      return this.getRoleName(this.userType)
    }
  },
  mounted () {
    this.getNameByUid()
    this.getAllInfoNeed()
  },
  data () {
    return {
      dialogVisible: false,
      fileTemp: {},
      excelList: [],
      userList: [],
      schoolName: '',
      users: []
    }
  },
  methods: {
    open () {
      this.dialogVisible = true
    },
    handleClose () {
      this.dialogVisible = false
    },
    handleChange (file, fileList) {
      this.fileTemp = file.raw
      if (this.fileTemp) {
        if ((this.fileTemp.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') ||
            (this.fileTemp.type === 'application/vnd.ms-excel')) {
          this.loadExcel(this.fileTemp, fileList)
        } else {
          this.$message({
            type: 'error',
            message: '附件格式错误，请删除后重新上传！'
          })
        }
      } else {
        this.$message({
          type: 'warning',
          message: '请上传附件！'
        })
      }
    },
    handleExceed () {
      this.$message({
        type: 'warning',
        message: '超出最大上传文件数量的限制！'
      })
    },
    handleRemove (file, fileList) {
      this.fileTemp = null
    },
    loadExcel (file1, fileList) {
      let data = readExcel(file1, 0)
      data.then((d) => {
        this.excelList = d
        this.changeToData(this.excelList)
      })
    },
    changeToData (jData) {
      let array1 = []
      jData.forEach((item) => {
        array1.push({
          name: item.name,
          age: item.age,
          account: item.account,
          passwd: item.passwd,
          phone: item.phone,
          email: item.email,
          role: item.role,
          city: item.city,
          province: item.province,
          schoolId: this.userId,
          schoolName: this.schoolName,
          grade: item.grade,
          gender: item.gender})
      })
      this.userList = array1
      console.log(this.userList)
    },
    insertExcel () {
      insertUser(this.userList)
      this.dialogVisible1 = false
      this.reload()
    },
    getNameByUid () {
      getNameByUid(this.userId).then((res) => {
        this.schoolName = res
      })
    },
    getAllInfoNeed () {
      getAllUserBySid(this.userId).then((res) => {
        this.users = res
      })
    }
  }
}
</script>

<style scoped>
.el-table th.el-table__cell{
  background-color: transparent;
}
/deep/ .el-table__header{
  background-color: transparent;
}
.el-table__header{
  background-color: transparent;
}
/*最外层透明*/
/deep/ .el-table, /deep/ .el-table__expanded-cell{
  background-color: transparent;
}
/* 表格内背景颜色 */
/deep/ .el-table th,
/deep/ .el-table tr,
/deep/ .el-table td {
  background-color: transparent;
}

.el-table::before {//去除底部白线
left: 0;
  bottom: 0;
  width: 100%;
  height: 0px;
}
</style>
